import pygame
import random

# 初始化Pygame
pygame.init()

# 游戏设置
GRID_SIZE = 20
CELL_SIZE = 20
GAME_WIDTH = 400
GAME_HEIGHT = 400

# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# 初始化游戏
screen = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT))
pygame.display.set_caption('贪吃蛇游戏')

clock = pygame.time.Clock()

# 蛇和食物
snake = [{'x': 10, 'y': 10}]
foods = [{'x': random.randint(0, (GAME_WIDTH // CELL_SIZE) - 1),
          'y': random.randint(0, (GAME_HEIGHT // CELL_SIZE) - 1)} for _ in range(180)]

direction = {'x': 0, 'y': 0}
game_speed = 15

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction['y'] == 0:
                direction = {'x': 0, 'y': -1}
            elif event.key == pygame.K_DOWN and direction['y'] == 0:
                direction = {'x': 0, 'y': 1}
            elif event.key == pygame.K_LEFT and direction['x'] == 0:
                direction = {'x': -1, 'y': 0}
            elif event.key == pygame.K_RIGHT and direction['x'] == 0:
                direction = {'x': 1, 'y': 0}

    # 更新蛇的位置
    head = {'x': snake[0]['x'] + direction['x'],
            'y': snake[0]['y'] + direction['y']}

    # 碰撞检测
    if head['x'] < 0: head['x'] = (GAME_WIDTH // CELL_SIZE) - 1
    elif head['x'] >= GAME_WIDTH // CELL_SIZE: head['x'] = 0
    if head['y'] < 0: head['y'] = (GAME_HEIGHT // CELL_SIZE) - 1
    elif head['y'] >= GAME_HEIGHT // CELL_SIZE: head['y'] = 0
    if head['x'] < 0: head['x'] = (GAME_WIDTH // CELL_SIZE) - 1
    elif head['x'] >= GAME_WIDTH // CELL_SIZE: head['x'] = 0
    if head['y'] < 0: head['y'] = (GAME_HEIGHT // CELL_SIZE) - 1
    elif head['y'] >= GAME_HEIGHT // CELL_SIZE: head['y'] = 0

    # 更新蛇的身体
    snake.insert(0, head)
    for i, food in enumerate(foods):
            if head['x'] == food['x'] and head['y'] == food['y']:
                foods[i] = {'x': random.randint(0, (GAME_WIDTH // CELL_SIZE) - 1),
                           'y': random.randint(0, (GAME_HEIGHT // CELL_SIZE) - 1)}
                break
    else:
        snake.pop()

    # 绘制游戏
    screen.fill(BLACK)
    for segment in snake:
        pygame.draw.rect(screen, GREEN, (segment['x'] * CELL_SIZE, segment['y'] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
    for food in foods:
            pygame.draw.rect(screen, RED, (food['x'] * CELL_SIZE, food['y'] * CELL_SIZE, CELL_SIZE, CELL_SIZE))

    pygame.display.flip()
    clock.tick(game_speed)

# 游戏结束
pygame.quit()
print('游戏结束！')